package com.netty.config;

import com.netty.CIMSocketRequestHandler;
import com.netty.constant.Constants;
import com.netty.constant.ImChannels;
import com.netty.model.proto.ReplyBodyProto;
import com.netty.model.proto.SentBodyProto;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import java.net.UnknownHostException;

/**
 * @author zl
 * @version 1.0
 * @date 2021/9/17 17:43
 */
@Slf4j
public class CIMSocketConfig implements CIMSocketRequestHandler {
    @Autowired
    private ImChannels imChannels;

    public CIMSocketConfig(ImChannels imChannels) throws UnknownHostException {
        this.imChannels = imChannels;
    }

    @Override
    public void channelActive(Channel channel) {
        System.out.println("链接成功");
    }

    @Override
    public void channelRead0(Channel channel, Object body) {
        if (body instanceof SentBodyProto.Model) {
            SentBodyProto.Model message = (SentBodyProto.Model) body;
            switch (message.getKey()){
                case Constants.ImserverConfig.CLIENT_CONNECT_BIND:
                    SentBodyProto.Model.Builder reply = SentBodyProto.Model.newBuilder();
                    reply.setKey(message.getKey());
                    reply.setTimestamp(System.currentTimeMillis());
                    String uid = message.getDataOrThrow("uid");
                    channel.attr(Constants.SessionConfig.UID).set(uid);
                    channel.attr(Constants.SessionConfig.CHANNEL).set(Constants.ImserverConfig.SOCKET);
                    channel.attr(Constants.SessionConfig.DEVICE_ID).set(message.getDataOrThrow("deviceId"));
                    /*
                     * 添加到内存管理
                     */
                    imChannels.add(channel);
                    /*
                     *向客户端发送bind响应
                     */
                    channel.writeAndFlush(reply);
                    break;
                case Constants.ImserverConfig.CLIENT_CONNECT_CLOSED:
                    channelUnregistered(channel);
                    break;
            }
        }
        /*
         * 发送上线事件到集群中的其他实例，控制其他设备下线
         */
        //signalRedisTemplate.bind(session);
    }

    @Override
    public void channelUnregistered(Channel channel) {
        imChannels.delete(channel);
    }
}
